<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'unsafe-inline';"
    />
    <title>electron-note</title>
    <link href="./loader.css" rel="stylesheet" />
  </head>
  <body>
    <nav></nav>
    <h4>
      <button class="btn btn-sm btn-primary" onclick="clickBackMainPageBtn();">
        返回主页
      </button>
      <button class="btn btn-sm btn-outline-primary" disabled>
        <span id="markdownFileName"></span
        ><b><span id="markdownFileChanged"></span></b>
      </button>
      <button
        class="btn btn-sm btn-primary"
        onclick="openMarkdownFile.stageStart()"
      >
        打开
      </button>
      <button class="btn btn-sm btn-primary" onclick="newEditorWindow()">
        新建
      </button>
      <button class="btn btn-sm btn-primary" onclick="saveMarkdownFile()">
        保存
      </button>
      <button class="btn btn-sm btn-primary" onclick="saveAsMarkdownFile()">
        另存为
      </button>
    </h4>
    <textarea
      id="editor_writing"
      class="form-control"
      style="
        position: fixed;
        top: 90px;
        width: 50%;
        height: calc(100% - 90px);
        font-family: 'Courier New', Courier, monospace;
        color: #153a7e;
        font-size: 16px;
        background-color: #f6f8fa;
      "
      spellcheck="false"
      placeholder="在这里输入 Markdown 代码"
    ></textarea>
    <div
      id="editor_preview"
      style="
        position: fixed;
        top: 90px;
        width: calc(50% - 4px);
        height: calc(100% - 90px);
        right: 0;
        overflow-y: scroll;
      "
      class="markdown-body"
    ></div>
    <!-- hidden file uploader -->
    <input
      type="file"
      id="markdownFileSelector"
      style="display: none"
      onchange="openMarkdownFile.stageSelected()"
    />
    <br />
    <!-- 在点击关闭按钮时询问是否保存文件的模态框 -->
    <div class="modal" tabindex="-1" id="ifWannaSaveFileDialogClose">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">在关闭前将更改保存到文件中？</h5>
          </div>
          <div class="modal-body">
            <p>如果你不保存，你对文档进行的编辑将会丢失。</p>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-primary"
              onclick="ifWannaSaveFileDialogClose_save()"
            >
              保存
            </button>
            <button
              type="button"
              class="btn btn-secondary"
              onclick="ifWannaSaveFileDialogClose_cancel()"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-secondary"
              onclick="ifWannaSaveFileDialogClose_dontsave()"
            >
              不保存
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 在点击返回主页按钮时询问是否保存文件的模态框 -->
    <div class="modal" tabindex="-1" id="ifWannaSaveFileDialogBackMainPage">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">在返回主页前将更改保存到文件中？</h5>
          </div>
          <div class="modal-body">
            <p>如果你不保存，你对文档进行的编辑将会丢失。</p>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-primary"
              onclick="ifWannaSaveFileDialogBackMainPage_save()"
            >
              保存
            </button>
            <button
              type="button"
              class="btn btn-secondary"
              onclick="ifWannaSaveFileDialogBackMainPage_cancel()"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-secondary"
              onclick="ifWannaSaveFileDialogBackMainPage_dontsave()"
            >
              不保存
            </button>
          </div>
        </div>
      </div>
    </div>

    <script src="app.js"></script>

    <script>
      var markdownEditorFilePath;
      var whoScrolling;

      var ifWannaSaveFileDialogClose = new bootstrap.Modal(
        document.querySelector("#ifWannaSaveFileDialogClose")
      );
      var ifWannaSaveFileDialogBackMainPage = new bootstrap.Modal(
        document.querySelector("#ifWannaSaveFileDialogBackMainPage")
      );

      function newEditorWindow() {
        let new_win_a = new BrowserWindow({
          width: 1000,
          height: 600,
          webPreferences: {
            nodeIntegration: true,
            enableRemoteModule: true,
          },
          frame: false,
        });

        new_win_a.loadURL("file://" + __dirname + "/editor.html");

        new_win_a.on("close", (e) => {
          e.preventDefault();
        });
      }

      const markdown_preview = () => {
        $("#editor_preview").html(
          marked($("#editor_writing").val()) + "<br /><br />"
        );
        // 路径改写
        if (markdownEditorFilePath !== undefined) {
          $("#editor_preview").append(
            `<img id="processDirNowTest" src="./" style="display:none;"></img>`
          );
          var markdownEditorFileDir = (
            path.dirname(markdownEditorFilePath) + "/"
          ).replace("file://", "");
          var processDirNowTest = document
            .querySelector("#processDirNowTest")
            .src.replace("file://", "");
          // 图像路径改写为markdown文件所在路径
          for (var i = 0; i < $("#editor_preview").find("img").length; i++) {
            if (
              $("#editor_preview").find("img")[i].src.indexOf("https://") !==
                -1 ||
              $("#editor_preview").find("img")[i].src.indexOf("http://") !== -1
            ) {
              //图像并非本地文件，无需改写路径
            } else {
              // 图像来自本地，需要改写路径
              var relatedPath = path.relative(
                processDirNowTest,
                $("#editor_preview").find("img")[i].src.replace("file://", "")
              );
              $("#editor_preview").find("img")[i].src =
                markdownEditorFileDir + relatedPath;
            }
          }
          // 链接路径改写
          for (var i = 0; i < $("#editor_preview").find("a").length; i++) {
            var tempLocationLink = $("#editor_preview")
              .find("a")
              [i].href.replace("file://", "");
            //case1:链接指向网页地址，则点击链接时用本地浏览器打开
            if (
              $("#editor_preview").find("a")[i].href.indexOf("http://") !==
                -1 ||
              $("#editor_preview").find("a")[i].href.indexOf("https://") !== -1
            ) {
              $("#editor_preview").find("a")[
                i
              ].href = `javascript:shell.openExternal("${tempLocationLink}")`;
            } else {
              // case2: 链接指向本地，在文件夹中打开
              $("#editor_preview").find("a")[
                i
              ].href = `javascript:shell.showItemInFolder("${tempLocationLink}")`;
            }
          }
        }
      };

      function keyEventFxDown() {
        if (
          event.keyCode == 83 &&
          (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)
        ) {
          saveMarkdownFile();
        }
      }

      function keyEventFxUp() {
        markdown_preview();
        scrollSyncChange("preview跟着writing滚");
        isMarkdownFileChanged = true;
        $("#markdownFileChanged").html("*");
      }

      document.onkeydown = keyEventFxDown;
      document.querySelector("#editor_writing").onkeyup = keyEventFxUp;

      document.querySelector("#editor_preview").onmousemove = () => {
        scrollSyncChange("writing跟着preview滚");
      };
      document.querySelector("#editor_writing").onmousemove = () => {
        scrollSyncChange("preview跟着writing滚");
      };

      if (getUrlArgs("filepath") !== false) {
        let filepath = decodeURIComponent(getUrlArgs("filepath")).replace("file://","");
        fs.readFile(filepath, "utf8", function (err, data) {
          document.querySelector("#editor_writing").value = data;
          markdown_preview();
        });
        $("#markdownFileName").text(path.basename(filepath));
        markdownEditorFilePath = filepath;
      }

      if (markdownEditorFilePath === undefined) {
        $("#markdownFileName").text("untitled");
      }

      // 同步滚动(编辑→预览)
      $("#editor_writing").scroll(function () {
        if (whoScrolling !== "writing跟着preview滚") {
          whoScrolling = "preview跟着writing滚";
          console.log(whoScrolling);
          var ih =
            document.querySelector("#editor_writing").scrollHeight -
            $("#editor_writing").height();
          var oh =
            document.querySelector("#editor_preview").scrollHeight -
            $("#editor_preview").height();
          var ipn = document.querySelector("#editor_writing").scrollTop;

          document.querySelector("#editor_preview").scrollTop = (ipn / ih) * oh;
        }
      });
      // 同步滚动(预览→编辑)
      $("#editor_preview").scroll(function () {
        if (whoScrolling !== "preview跟着writing滚") {
          whoScrolling = "writing跟着preview滚";
          console.log(whoScrolling);
          var ih =
            document.querySelector("#editor_writing").scrollHeight -
            $("#editor_writing").height();
          var oh =
            document.querySelector("#editor_preview").scrollHeight -
            $("#editor_preview").height();
          var ipn = document.querySelector("#editor_preview").scrollTop;

          document.querySelector("#editor_writing").scrollTop = (ipn / oh) * ih;
        }
      });

      function scrollSyncChange(changeToWhat) {
        whoScrolling = changeToWhat;
      }
    </script>
  </body>
</html>
